package com.wing.cabinet.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wing.cabinet.model.entity.StoresRequisition;
import com.wing.cabinet.model.request.StoresRequisitionForm;
import com.wing.cabinet.model.request.TakeDeliveryForm;
import com.wing.cabinet.model.response.CabinetVO;
import com.wing.cabinet.model.response.StoresRequisitionProductVO;
import com.wing.cabinet.model.response.StoresRequisitionVO;
import com.wing.cabinet.service.AuthorityManageService;
import com.wing.cabinet.service.CabinetService;
import com.wing.cabinet.service.StoresRequisitionProductService;
import com.wing.cabinet.service.StoresRequisitionService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.Result;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.sms.feign.SmsClient;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "App-领新申请表管理", tags = "领新申请表管理")
@RestController("appStoresRequisitionController")
@RequestMapping("cabinet/app/storesRequisition")
public class StoresRequisitionController {

    @Autowired
    private StoresRequisitionService storesRequisitionService;
    @Autowired
    private LocaleMessage localeMessage;
    @Autowired
    private StoresRequisitionProductService storesRequisitionProductService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private CabinetService cabinetService;
    @Autowired
    private SmsClient smsClient;
    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private AuthorityManageService authorityManageService;

    @ApiOperation(value = "查询所有领新申请", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "cabinetCode", value = "刀柜编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "userId", value = "领取人id", defaultValue = "", example = "", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<StoresRequisitionVO> list(
            @RequestParam(name = "page",  required = false) Integer page
            ,@RequestParam(name = "limit",  required = false) Integer limit
            ,@RequestParam(name = "sort",required = false) String sort
            ,@RequestParam(name = "order", required = false) String order
            ,StoresRequisitionVO storesRequisitionVO
            ,StoresRequisition.CheckStatus checkStatus
            ,StoresRequisition.Status status
    ){
        //搜索
        if(storesRequisitionVO.getSourceType() == null){
            storesRequisitionVO.setUserId(JwtUtils.getLoginUserId());
        }
        IPage<StoresRequisitionVO> list = storesRequisitionService.getStoresRequisitionVOPageList(storesRequisitionVO,checkStatus,status,page,limit);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/{id}")
    public JsonResult detail(@PathVariable("id") Long storesRequisitionId) {
        StoresRequisitionVO storesRequisitionVO = storesRequisitionService.get4appById(storesRequisitionId);
        if (storesRequisitionVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), storesRequisitionVO);
    }

    @ApiOperation(value = "添加领新申请表", notes = "添加")
    @PostMapping("/submitStoresRequisition")
    public JsonResult submitStoresRequisition(@RequestBody StoresRequisitionForm storesRequisitionForm) {
        try {
            storesRequisitionService.submitStoresRequisitionForm(storesRequisitionForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("添加领新申请接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "查询领新申请产品信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "storesRequisitionId", value = "领新申请id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/storesRequisitionProductPageList")
    public PageResult<StoresRequisitionProductVO> storesRequisitionProductPageList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long storesRequisitionId
    ){
        //搜索
        IPage<StoresRequisitionProductVO> list = storesRequisitionProductService.getStoresRequisitionProductVOPageList(storesRequisitionId,page,limit);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "修改领新申请表（审核）", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(StoresRequisitionForm.Update.class) StoresRequisitionForm storesRequisitionForm) {
        StoresRequisition storesRequisition = storesRequisitionService.getById(storesRequisitionForm.getId());
        if(storesRequisition == null){
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(StoresRequisition.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(storesRequisitionForm, storesRequisition, copyOptions);
        if(storesRequisitionForm.getCheckStatus() != null){
            storesRequisition.setAuditPerson(JwtUtils.getLoginUsername());
            storesRequisition.setAuditTime(LocalDateTime.now());
            storesRequisition.setStatus(StoresRequisition.Status.checked);
        }
        if (storesRequisitionService.updateById(storesRequisition)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "校验密码", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storesRequisitionId", value = "领新申请id", required = true, dataType = "Integer", paramType = "path")
            ,@ApiImplicitParam(name = "instructionCode", value = "领货密码", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/verifyInstructionCode")
    public JsonResult verifyInstructionCode(@RequestParam("storesRequisitionId")  Long storesRequisitionId
            ,@RequestParam("instructionCode") Integer instructionCode){
        StoresRequisitionVO requisitionVO = storesRequisitionService.get4appById(storesRequisitionId);
        if(requisitionVO == null){
            JsonResult.fail("领新申请数据异常");
        }
        if(!requisitionVO.getLnstructionCode().equals(instructionCode)){
            JsonResult.fail("领货密码错误，请重新输入！");
        }

        return JsonResult.success("操作成功");
    }

    @ApiOperation(value = "查询领新工单信息和产品信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storesRequisitionId", value = "领新申请id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getWorkOrderInfo")
    public JsonResult<StoresRequisitionVO> getWorkOrderInfo(@RequestParam("storesRequisitionId") Long storesRequisitionId){
        StoresRequisitionVO requisitionVO = storesRequisitionService.getWorkOrderInfo(storesRequisitionId);
        return JsonResult.success(requisitionVO);

    }

    @ApiOperation(value = "领取产品", notes = "添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "takeDeliveryForm", value = "领取产品对象", required = true, dataType = "object", paramType = "path")
    })
    @PostMapping("/getRequisitionProduct")
    public JsonResult getRequisitionProduct(@RequestBody TakeDeliveryForm takeDeliveryForm) {
        try {
            storesRequisitionService.submitGetRequisitionProduct(takeDeliveryForm);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("领取产品接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "查询主柜编号", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "辅柜编号", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/getCabinetVoByCode")
    public JsonResult<CabinetVO> getCabinetVoByCode(@RequestParam("code") String code){
        CabinetVO cabinet = cabinetService.get4appByCode(code);
        return JsonResult.success(cabinet);

    }
    @ApiOperation(value = "领新申请发送短信通知", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storesRequisitionId", value = "领新申请表id", required = true, dataType = "Integer", paramType = "path")
    })
    @GetMapping("/sendInstruct")
    public JsonResult sendInstruct(@RequestParam("storesRequisitionId") Long storesRequisitionId) {
        StoresRequisitionVO storesRequisitionVO = storesRequisitionService.get4appById(storesRequisitionId);
        if (storesRequisitionVO == null) {
            return JsonResult.success("领新申请数据异常");
        }
        JsonResult<UserVO> userInfo = userClient.getUserInfo(storesRequisitionVO.getUserId());
        if(userInfo.getData() == null){
            return JsonResult.success("领取人不存在");
        }
        JsonResult result = smsClient.sendNoticeCode(userInfo.getData().getPhone(), storesRequisitionVO.getCode());
        if(result.getCode() == Result.Code.SUCCESS.getCode()) {
            return JsonResult.success("发送成功！");
              /*  JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(result.getData()).toString());
                if (null != jsonObject && StringUtils.isNotBlank(jsonObject.getString("key"))) {
                    return JsonResult.success("发送成功！", jsonObject);
                }*/
        }
        return JsonResult.fail("发送失败");
    }

    @ApiOperation(value = "查询产品(对外api接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "skuCode", value = "sku编号", required = false, dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "cabinetId", value = "刀柜ID", required = true, dataType = "String", paramType = "query")

    })
    @GetMapping("/getProductDetailPageList")
    public PageResult<ProductDetailVO> getProductDetailPageList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(value = "skuCode",required = false) String skuCode
            ,@RequestParam(value = "cabinetId") Long cabinetId
    ){
        //柜子查看产品分类权限
        String categoryIds = authorityManageService.getCabinetProductAuthority(cabinetId);
        PageResult<ProductDetailVO> pageList = enterpriseClient.getProductPageList(page, limit, skuCode, categoryIds);
        return new PageResult<>(pageList.getData(), pageList.getCount());
    }

}
